# -*- coding: utf-8 -*-
# @Author : HaleShi
# @Time : 2023-07-11
# @File : 11_set_code.py

import base64
import requests
import json
import time
import random
import cv2
import numpy as np
import uuid
from urllib.parse import quote


def get_image_object(bs_image):
    obj = base64.b64decode(bytes(bs_image, encoding="ascii"))
    img_buffer_np = np.frombuffer(obj, dtype=np.uint8)
    # 从指定的内存缓存中读取一维numpy数据, 并把数据转换(解码)成图像矩阵格式
    img_np = cv2.imdecode(img_buffer_np, 1)
    bg_img = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
    return bg_img


def get_distance(l_image_object, s_image_object):
    # 边缘检测
    bg_edge = cv2.Canny(l_image_object, 255, 255)
    tp_edge = cv2.Canny(s_image_object, 255, 255)

    bg_pic = cv2.cvtColor(bg_edge, cv2.COLOR_GRAY2RGB)
    tp_pic = cv2.cvtColor(tp_edge, cv2.COLOR_GRAY2RGB)

    res = cv2.matchTemplate(bg_pic, tp_pic, cv2.TM_CCOEFF_NORMED)

    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)  # 寻找最优匹配
    x = max_loc[0]
    return x


res = requests.post(
    url='https://m.captcha.qq.com/',
    data='{"Action":"CheckCaptchaAppId_v1.0.1","CaptchaAppId":2075530305}',
)
esid = res.json()['Response']['SId']

res = requests.post(
    url='https://m.captcha.qq.com/',
    data='{"Action":"GetImageData_v1.0.1","ESId":"%s"}' % esid,
)
data_dict = res.json()

l_image = data_dict['Response']['ImageDataL']
l_image_object = get_image_object(l_image)

s_image = data_dict['Response']['ImageDataS']
s_image_object = get_image_object(s_image)
distance = get_distance(l_image_object, s_image_object)

sid = data_dict['Response']['UniqueSId']

# 提交滑块
time.sleep(random.randint(3, 5))    #太快了 会提示操作频繁
data = '{"Action":"VerificationCaptchaImageAnswer_v1.0.1","UniqueSId":"%s","LeftTopX":"%s","ranNum":0,"Frequency":1}' % (
    sid, distance)
res = requests.post(
    url='https://m.captcha.qq.com/',
    data=data,
)

ticket = res.json()['Response']['Ticket']
tgs_uuid = str(uuid.uuid4())
tel = "18378353331"
data = f'sence=22&ticket={quote(ticket, "utf-8")}&cellPhone={tel}&__curPage__=pages%2Fcustomerlogin%2Fcustomerlogin'

resp = requests.post(
    url='https://service.51tiangou.com/mserv/applet/wechat/member/sendSms',
    data=data,
    headers={
        'content-type': 'application/x-www-form-urlencoded',
        'tgs_uuid': tgs_uuid,
        'city': "2554",
        'store': '20',
        'platform': 'wxapp-tg',
        'tgverion': '@tiangou/wxapp/20230704/1689056915499',
        'client-type': 'wx-app',
        'tgs_session': '6442',
        'Accept-Encoding': 'gzip,compress,br,deflate',
        'User-Agent': 'Mozilla/5.0 (Linux; Android 10; Pixel 2 XL Build/QQ3A.200805.001; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/107.0.5304.141 Mobile Safari/537.36 XWEB/5169 MMWEBSDK/20230303 MMWEBID/1692 MicroMessenger/8.0.34.2340(0x2800225F) WeChat/arm64 Weixin NetType/WIFI Language/en ABI/arm64 MiniProgramEnv/android'
    },
    cookies={
        'tgs_uuid': tgs_uuid
    }
)
data_dict = resp.json()
print(data_dict)
